package neves.android.etmg.pathfinding;

import java.util.Hashtable;

import neves.android.etmg.tilemap.TileMap;

public class TileMapNodeKeeper {
	private TileMap curTMap;
	private Hashtable pathNodeTable;

	public TileMapNodeKeeper(TileMap theMap) {
		curTMap = theMap;
		pathNodeTable = new Hashtable();
	}

	public TileMapPathNode getNode(int[] loc) {
		return getNode(loc[0], loc[1]);
	}

	public TileMapPathNode getNode(int x, int y) {

		String keyString = Integer.toString(x) + "_" + Integer.toString(y);

		TileMapPathNode resultNode = null;

		// check if the tile pos is legal
		if (curTMap.isOutofBound(x, y) || curTMap.isWallTile(x, y)) {

			return null;
		} else {

			// if already have the node
			if (pathNodeTable.containsKey(keyString)) {

				resultNode = (TileMapPathNode) (pathNodeTable.get(keyString));

			} else {
				resultNode = putNewNode(x, y);
			}

			// if is Goal Node then ignore legal of pos
			if (!resultNode.isGoalNode()&& curTMap.isCreatureOccupy(x, y)) {
				return null;
			}
	
			return resultNode;
		}

	}

	public TileMapPathNode putNewNode(int[] loc) {
		return putNewNode(loc[0], loc[1]);
	}

	public TileMapPathNode putNewNode(int x, int y) {

		String keyString = Integer.toString(x) + "_" + Integer.toString(y);

		TileMapPathNode newNode = null;

		newNode = new TileMapPathNode(this, new int[] { x, y });

		pathNodeTable.put(keyString, newNode);

		return newNode;
	}

}
